package cn.aws360.boot.data.api.handler;

import cn.aws360.boot.auth.api.helper.LoginHelper;
import cn.aws360.boot.base.api.constant.enums.DelFlagEnum;
import cn.aws360.boot.data.api.constant.DataConstant;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.util.ClassUtils;

import java.nio.charset.Charset;
import java.time.LocalDateTime;

/**
 * @author junnan
 */
@Slf4j
public class CustomMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("mybatis plus start insert fill ....");
        LocalDateTime now = LocalDateTime.now();
        fillValIfNullByName(DataConstant.DEL_FLAG, DelFlagEnum.N.getValue(), metaObject, false);
        fillValIfNullByName(DataConstant.CREATE_BY, getUserName(), metaObject, false);
        fillValIfNullByName(DataConstant.CREATE_TIME, now, metaObject, false);
        fillValIfNullByName(DataConstant.UPDATE_BY, getUserName(), metaObject, false);
        fillValIfNullByName(DataConstant.UPDATE_TIME, now, metaObject, false);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("mybatis plus start update fill ....");
        fillValIfNullByName(DataConstant.UPDATE_BY, getUserName(), metaObject, true);
        fillValIfNullByName(DataConstant.UPDATE_TIME, LocalDateTime.now(), metaObject, true);
    }

    private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
        // 0. 如果填充值为空
        if (ObjectUtil.isNull(fieldVal)) {
            return;
        }
        // 1. 没有 get 方法
        if (!metaObject.hasSetter(fieldName)) {
            return;
        }
        // 2. 如果用户有手动设置的值
        Object userSetValue = metaObject.getValue(fieldName);
        String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
        if (StrUtil.isNotBlank(setValueStr) && !isCover) {
            return;
        }
        // 3. field 类型相同时设置
        Class<?> getterType = metaObject.getGetterType(fieldName);
        if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
            metaObject.setValue(fieldName, fieldVal);
        }
    }

    private String getUserName() {
        return LoginHelper.getUsername();
    }

}
